package com.company.aicrawlers.controller.api;

import com.company.aicrawlers.common.dto.ApiResponse;
import com.company.aicrawlers.common.dto.PageResponse;
import com.company.aicrawlers.entity.Product;
import com.company.aicrawlers.entity.Question;
import com.company.aicrawlers.entity.QuestionCategory;
import com.company.aicrawlers.entity.QuestionProduct;
import com.company.aicrawlers.service.QuestionCategoryService;
import com.company.aicrawlers.service.QuestionProductService;
import com.company.aicrawlers.service.QuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 问句API控制器
 *
 * @author AI Crawlers Team
 * @date 2025-10-10
 */
@Slf4j
@RestController
@RequestMapping("/api/questions")
public class QuestionApiController {
    
    @Autowired
    private QuestionService questionService;
    
    @Autowired
    private QuestionProductService questionProductService;
    
    @Autowired
    private QuestionCategoryService questionCategoryService;
    
    /**
     * 分页查询问句列表（增强版，支持按产品/类别筛选）
     * 
     * 接口：GET /api/questions
     *
     * @param page 页码，默认1
     * @param size 每页大小，默认10
     * @param keyword 搜索关键词
     * @param category 问句类别
     * @param productId 产品ID（筛选关联该产品的问句）
     * @param productCategoryId 产品类别ID
     * @param status 状态
     * @return 分页数据
     */
    @GetMapping(value = "", name = "getQuestionList")
    public ApiResponse<PageResponse<Question>> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) Long productId,
            @RequestParam(required = false) Long productCategoryId,
            @RequestParam(required = false) Integer status
    ) {
        log.info("查询问句列表，page: {}, size: {}, keyword: {}, category: {}, productId: {}, productCategoryId: {}, status: {}", 
                page, size, keyword, category, productId, productCategoryId, status);
        
        // 如果有产品或类别筛选条件，使用增强查询
        if (productId != null || productCategoryId != null) {
            PageResponse<Question> pageData = questionService.getPageListEnhanced(
                    page, size, keyword, category, productId, productCategoryId, status);
            return ApiResponse.success(pageData);
        }
        
        // 否则使用普通查询
        PageResponse<Question> pageData = questionService.getPageList(page, size, keyword, category, status);
        return ApiResponse.success(pageData);
    }
    
    /**
     * 获取问句详情
     * 
     * 接口：GET /api/questions/{id}
     *
     * @param id 问句ID
     * @return 问句对象
     */
    @GetMapping(value = "/{id}", name = "getQuestionById")
    public ApiResponse<Question> getById(@PathVariable("id") Long id) {
        log.info("获取问句详情，id: {}", id);
        
        Question question = questionService.getById(id);
        return ApiResponse.success(question);
    }
    
    /**
     * 创建问句
     * 
     * 接口：POST /api/questions
     *
     * @param question 问句对象
     * @return 问句ID
     */
    @PostMapping(value = "", name = "createQuestion")
    public ApiResponse<Long> create(@RequestBody Question question) {
        log.info("创建问句，content: {}", question.getQuestionContent());
        
        Long questionId = questionService.create(question);
        return ApiResponse.success(questionId, "创建成功");
    }
    
    /**
     * 更新问句
     * 
     * 接口：PUT /api/questions/{id}
     *
     * @param id 问句ID
     * @param question 问句对象
     * @return 成功消息
     */
    @PutMapping(value = "/{id}", name = "updateQuestion")
    public ApiResponse<Void> update(@PathVariable("id") Long id, @RequestBody Question question) {
        log.info("更新问句，id: {}", id);
        
        question.setQuestionId(id);
        questionService.update(question);
        return ApiResponse.success("更新成功");
    }
    
    /**
     * 删除问句
     * 
     * 接口：DELETE /api/questions/{id}
     *
     * @param id 问句ID
     * @return 成功消息
     */
    @DeleteMapping(value = "/{id}", name = "deleteQuestion")
    public ApiResponse<Void> delete(@PathVariable("id") Long id) {
        log.info("删除问句，id: {}", id);
        
        questionService.delete(id);
        return ApiResponse.success("删除成功");
    }
    
    /**
     * 批量删除问句
     * 
     * 接口：DELETE /api/questions/batch
     *
     * @param ids 问句ID列表
     * @return 成功消息
     */
    @DeleteMapping(value = "/batch", name = "batchDeleteQuestions")
    public ApiResponse<Void> batchDelete(@RequestBody List<Long> ids) {
        log.info("批量删除问句，ids: {}", ids);
        
        questionService.batchDelete(ids);
        return ApiResponse.success("批量删除成功");
    }
    
    /**
     * 批量导入问句（Excel）
     * 
     * 接口：POST /api/questions/import
     *
     * @param file Excel文件
     * @return 导入数量
     */
    @PostMapping(value = "/import", name = "importQuestions")
    public ApiResponse<Integer> batchImport(@RequestParam("file") MultipartFile file) {
        log.info("批量导入问句，文件名: {}", file.getOriginalFilename());
        
        Integer count = questionService.batchImport(file);
        return ApiResponse.success(count, "成功导入 " + count + " 条数据");
    }
    
    /**
     * 获取所有问句类别
     * 
     * 接口：GET /api/questions/categories
     *
     * @return 类别列表
     */
    @GetMapping(value = "/categories", name = "getAllCategories")
    public ApiResponse<List<String>> getAllCategories() {
        log.info("获取所有问句类别");
        
        List<String> categories = questionService.getAllCategories();
        return ApiResponse.success(categories);
    }
    
    // ==================== 问句-产品关联管理 ====================
    
    /**
     * 获取问句关联的所有产品
     * 
     * 接口：GET /api/questions/{id}/products
     *
     * @param id 问句ID
     * @return 产品列表
     */
    @GetMapping(value = "/{id}/products", name = "getQuestionRelatedProducts")
    public ApiResponse<List<Product>> getRelatedProducts(@PathVariable("id") Long id) {
        log.info("获取问句关联产品，问句ID: {}", id);
        
        List<Product> products = questionProductService.getProductsByQuestionId(id);
        return ApiResponse.success(products);
    }
    
    /**
     * 添加问句-产品关联
     *
     * @param id 问句ID
     * @param relation 关联对象
     * @return 关联ID
     */
    @PostMapping(value = "/{id}/products", name = "addQuestionProductRelation")
    public ApiResponse<Long> addProductRelation(
            @PathVariable("id") Long id,
            @RequestBody QuestionProduct relation
    ) {
        log.info("添加问句-产品关联，问句ID: {}, 产品ID: {}", id, relation.getProductId());
        
        Long relationId = questionProductService.addRelation(
                id,
                relation.getProductId(),
                relation.getRelationType(),
                relation.getSortOrder()
        );
        
        return ApiResponse.success(relationId, "添加关联成功");
    }
    
    /**
     * 批量设置问句的产品关联
     *
     * @param id 问句ID
     * @param relations 关联列表
     * @return 成功消息
     */
    @PutMapping(value = "/{id}/products/batch", name = "batchSetQuestionProducts")
    public ApiResponse<Void> batchSetProductRelations(
            @PathVariable("id") Long id,
            @RequestBody List<QuestionProduct> relations
    ) {
        log.info("批量设置问句产品关联，问句ID: {}, 关联数: {}", id, relations.size());
        
        questionProductService.batchSetRelations(id, relations);
        return ApiResponse.success("批量设置成功");
    }
    
    /**
     * 移除问句-产品关联
     *
     * @param id 问句ID
     * @param productId 产品ID
     * @return 成功消息
     */
    @DeleteMapping(value = "/{id}/products/{productId}", name = "removeQuestionProductRelation")
    public ApiResponse<Void> removeProductRelation(
            @PathVariable("id") Long id,
            @PathVariable("productId") Long productId
    ) {
        log.info("移除问句-产品关联，问句ID: {}, 产品ID: {}", id, productId);
        
        questionProductService.removeRelation(id, productId);
        return ApiResponse.success("移除成功");
    }
    
    // ==================== 问句-类别关联管理 ====================
    
    /**
     * 获取问句关联的所有产品类别
     *
     * @param id 问句ID
     * @return 类别名称列表
     */
    @GetMapping(value = "/{id}/product-categories", name = "getQuestionRelatedCategories")
    public ApiResponse<List<String>> getRelatedProductCategories(@PathVariable("id") Long id) {
        log.info("获取问句关联产品类别，问句ID: {}", id);
        
        List<String> categories = questionCategoryService.getCategoryNamesByQuestionId(id);
        return ApiResponse.success(categories);
    }
    
    /**
     * 添加问句-产品类别关联
     *
     * @param id 问句ID
     * @param relation 关联对象
     * @return 关联ID
     */
    @PostMapping(value = "/{id}/product-categories", name = "addQuestionCategoryRelation")
    public ApiResponse<Long> addCategoryRelation(
            @PathVariable("id") Long id,
            @RequestBody QuestionCategory relation
    ) {
        log.info("添加问句-类别关联，问句ID: {}, 类别ID: {}", id, relation.getCategoryId());
        
        Long relationId = questionCategoryService.addRelation(
                id,
                relation.getCategoryId(),
                relation.getCategoryName(),
                relation.getSortOrder()
        );
        
        return ApiResponse.success(relationId, "添加关联成功");
    }
    
    /**
     * 批量设置问句的产品类别关联
     *
     * @param id 问句ID
     * @param relations 关联列表
     * @return 成功消息
     */
    @PutMapping(value = "/{id}/product-categories/batch", name = "batchSetQuestionCategories")
    public ApiResponse<Void> batchSetCategoryRelations(
            @PathVariable("id") Long id,
            @RequestBody List<QuestionCategory> relations
    ) {
        log.info("批量设置问句类别关联，问句ID: {}, 关联数: {}", id, relations.size());
        
        questionCategoryService.batchSetRelations(id, relations);
        return ApiResponse.success("批量设置成功");
    }
    
    /**
     * 移除问句-产品类别关联
     *
     * @param id 问句ID
     * @param categoryId 类别ID
     * @return 成功消息
     */
    @DeleteMapping(value = "/{id}/product-categories/{categoryId}", name = "removeQuestionCategoryRelation")
    public ApiResponse<Void> removeCategoryRelation(
            @PathVariable("id") Long id,
            @PathVariable("categoryId") Long categoryId
    ) {
        log.info("移除问句-类别关联，问句ID: {}, 类别ID: {}", id, categoryId);
        
        questionCategoryService.removeRelation(id, categoryId);
        return ApiResponse.success("移除成功");
    }
    
    // ==================== 反向查询 ====================
    
    /**
     * 根据产品ID查询关联的问句ID列表
     *
     * @param productId 产品ID
     * @return 问句ID列表
     */
    @GetMapping(value = "/by-product/{productId}", name = "getQuestionsByProduct")
    public ApiResponse<List<Long>> getQuestionIdsByProduct(@PathVariable("productId") Long productId) {
        log.info("根据产品查询问句，产品ID: {}", productId);
        
        List<Long> questionIds = questionProductService.getQuestionIdsByProductId(productId);
        return ApiResponse.success(questionIds);
    }
    
    /**
     * 根据产品类别查询关联的问句ID列表
     *
     * @param categoryName 类别名称
     * @return 问句ID列表
     */
    @GetMapping(value = "/by-category/{categoryName}", name = "getQuestionsByCategory")
    public ApiResponse<List<Long>> getQuestionIdsByCategory(@PathVariable("categoryName") String categoryName) {
        log.info("根据类别查询问句，类别名称: {}", categoryName);
        
        List<Long> questionIds = questionCategoryService.getQuestionIdsByCategoryName(categoryName);
        return ApiResponse.success(questionIds);
    }
    
    /**
     * 批量获取问句详情
     *
     * @param requestBody 请求体，包含questionIds数组
     * @return 问句详情列表
     */
    @PostMapping(value = "/batch-get", name = "batchGetQuestions")
    public ApiResponse<List<Question>> batchGet(@RequestBody java.util.Map<String, Object> requestBody) {
        @SuppressWarnings("unchecked")
        List<Integer> questionIdInts = (List<Integer>) requestBody.get("questionIds");
        
        List<Long> questionIds = questionIdInts.stream()
                .map(Long::valueOf)
                .collect(java.util.stream.Collectors.toList());
        
        log.info("批量获取问句详情，问句数量: {}", questionIds.size());
        
        List<Question> questions = (List<Question>) questionService.listByIds(questionIds);
        return ApiResponse.success(questions);
    }
}

